package dk.hojlind.hackhunt.model;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketTimeoutException;

public class ClientSocket {

	//Public variables

	//Private variables
	String address;
	String line;
	String end = "\r\n.\r\n";
	int port;
	int timeout = 1000;
	Socket client;
	DataOutputStream output;
	InputStreamReader input;
	BufferedReader stringInput;
	String result;
	String error = "error";
	String timeoutError = "error: Could not obtain a connection to the server";

	//Constructor
	public ClientSocket(String address, int port)
	{
		//Get adress and port and then connect and create out and input
		this.address = address;
		this.port = port;
		client = new Socket();
	}
	
	//Send user info and await information, then save result and close everything
	public String processRequest(String message)
	{
		try 
		{
			message = message + end;
			client.connect(new InetSocketAddress(address, port), timeout);
			output = new DataOutputStream(client.getOutputStream());
			stringInput = new BufferedReader(new InputStreamReader(client.getInputStream()));
			output.writeBytes(message);
			
			while((line = stringInput.readLine()) != null && !line.equals("."))
            {
                result = result + line + "\r\n";
            }
			System.out.println(result);

			output.close();			
			stringInput.close();			
			client.close();
			return result;
		} 		
		catch (SocketTimeoutException se)
		{
			se.printStackTrace();
			return timeoutError;
		}
		catch (IOException e) 
		{
			e.printStackTrace();
		}
		
		return error;
	}
}
